package ktvutil

import (
	"bytes"
	"ktvserver/ktvutil/crypto/blowfish"
	"math/rand"
	"time"
)

// 获取随机数
func GetRamdomUint32() uint32 {
	rand.Seed(time.Now().UnixNano())
	return uint32(rand.Uint32())
}

// blowfish 加密数据
func BlowFishEncodeData(data []byte, key []byte) ([]byte, error) {

	srcData := blowfishChecksizeAndPad(data)

	// 初始化blowfish

	cipher1, err2 := blowfish.NewCipher(key)
	if err2 != nil {
		return []byte{}, err2
	}

	totalLen := len(data)

	// 加密后的数据
	dstBuf := new(bytes.Buffer)

	// blowfish 每次只能加密8个字节, 超过
	tempBuf := make([]byte, blowfish.BlockSize)

	for i := 0; i < totalLen; i = i + blowfish.BlockSize {
		cipher1.Encrypt(tempBuf, srcData[i:])
		dstBuf.Write(tempBuf)
	}

	return dstBuf.Bytes(), nil
}

// blowfish 解密数据
func BlowFishDecodeData(data []byte, key []byte) ([]byte, error) {

	srcData := blowfishChecksizeAndPad(data)

	// 初始化blowfish
	cipher1, err2 := blowfish.NewCipher(key)
	if err2 != nil {
		return []byte{}, err2
	}

	totalLen := len(data)
	//outputlen := GetOutputSize(totalLen)

	// 加密后的数据
	dstBuf := new(bytes.Buffer)

	// blowfish 每次只能加密8个字节, 超过
	tempBuf := make([]byte, blowfish.BlockSize)

	for i := 0; i < totalLen; i = i + blowfish.BlockSize {
		cipher1.Decrypt(tempBuf, srcData[i:])
		dstBuf.Write(tempBuf)
	}

	return dstBuf.Bytes(), nil
}

func blowfishChecksizeAndPad(pt []byte) []byte {
	// calculate modulus of plaintext to blowfish's cipher block size
	// if result is not 0, then we need to pad
	modulus := len(pt) % blowfish.BlockSize
	if modulus != 0 {
		// how many bytes do we need to pad to make pt to be a multiple of blowfish's block size?
		padlen := blowfish.BlockSize - modulus
		// let's add the required padding
		for i := 0; i < padlen; i++ {
			// add the pad, one at a time
			pt = append(pt, 0)
		}
	}
	// return the whole-multiple-of-blowfish.BlockSize-sized plaintext to the calling function
	return pt
}
